﻿# ------------------------------------------ #
# Azure Active Directory (AAD) Configuration #
# ------------------------------------------ #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing Azure Active Directory '$($script.type)' configuration ... " -NoNewLine $true
$session = Get-VirtualMachineInstancePowerShellSession -Subscription $subscription -VirtualMachineName $virtualMachineName
switch ($script.type)
{
	"Add User"
	{
		Invoke-Command -Session $session -ScriptBlock {
		    param([string]$adminUserName, [string]$adminPassword, [string]$userName, [string]$password, [string]$displayName)
            Import-Module MSOnline
            $credential = New-Object System.Management.Automation.PSCredential($adminUserName, (ConvertTo-SecureString $adminPassword -AsPlainText -Force))
            Connect-MsolService -Credential $credential
            if ((Get-MsolUser | ? { $_.UserPrincipalName -eq $userName}) -eq $null)
            {
                New-MsolUser -UserPrincipalName $userName -Password $password -DisplayName $displayName -ForceChangePassword $false -PasswordNeverExpires $true | Out-Null
            }
		} -ArgumentList $subscription.adminUserName, $subscription.password, $script.userName, $script.password, $script.displayName
    }
	"Add Role Member"
	{
		Invoke-Command -Session $session -ScriptBlock {
		    param([string]$adminUserName, [string]$adminPassword, [string]$name, [string]$userName)
            Import-Module MSOnline
            $credential = New-Object System.Management.Automation.PSCredential($adminUserName, (ConvertTo-SecureString $adminPassword -AsPlainText -Force))
            Connect-MsolService -Credential $credential
            if ((Get-MsolRoleMember -RoleObjectId (Get-MsolRole -RoleName $name).ObjectId | ? { $_.EmailAddress -eq $userName}) -eq $null)
            {
                Add-MsolRoleMember -RoleName $name -RoleMemberObjectId (Get-MsolUser -UserPrincipalName $userName).ObjectId | Out-Null
            }
		} -ArgumentList $subscription.adminUserName, $subscription.password, $script.name, $script.userName
    }
	default
	{
		throw "Azure Active Directory type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."